import { inHooks } from './compose/pd'

export function mix (...mixins) {
  return (()=>{
    class Mix {
      constructor(model) {
        const args = Array.prototype.slice.call(arguments)
        for (let mixin of mixins) {
          copyProperties(this, new mixin(...args)); // 拷贝实例属性
        }
      }
    }
    Mix.__inits__ = []

    for (let mixin of mixins) {
      copyProperties(Mix, mixin); // 拷贝静态属性
      copyProperties(Mix.prototype, mixin.prototype, Mix); // 拷贝原型属性
    }


    return Mix;
  })(mixins)
  // class Mix {
  //   constructor( model ) {
  //     const args = Array.prototype.slice.call(arguments)
  //     for (let mixin of mixins) {
  //       copyProperties(this, new mixin(...args)); // 拷贝实例属性
  //     }
  //   }
  // }
  // Mix.__inits__ = []

  // for (let mixin of mixins) {
  //   copyProperties(Mix, mixin); // 拷贝静态属性
  //   copyProperties(Mix.prototype, mixin.prototype, Mix); // 拷贝原型属性
  // }


  // return Mix;
}
// 深拷贝
export function copyProperties (target, source, Ctor, sub = false) {
  let init_key = !sub ? '__inits__' : ('__inits_' + source.constructor.name + "__")

  for (let key of Reflect.ownKeys(source)) {
    if (key !== 'constructor' && key !== 'prototype' && key !== 'name' && key !== 'init' && key !== 'elEvents' && !inHooks(key)) {
      let desc = Object.getOwnPropertyDescriptor(source, key);
      Object.defineProperty(target, key, desc);
    }else if(Ctor && key === 'init'){
      Ctor[init_key] = Ctor[init_key] || []
      Ctor[init_key].push( source.init )
    } else if (Ctor && inHooks(key)) {
      Ctor[init_key] = Ctor[init_key] || []
      Ctor[init_key].push(function () {
        const args = Array.prototype.slice.call(arguments)
        this.on(key, source[key])
      })
    } else if( Ctor && key === 'elEvents'){
      Ctor.__elevents__ = Ctor.__elevents__ || []
      Ctor.__elevents__.push( source[key] )
    }
  }
}

export default {
  mix,
  copyProperties
}